<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Group
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

bx_import('BxDolTwigPageView');

class BxGroupsPageView extends BxDolTwigPageView {	

	function BxGroupsPageView(&$oMain, &$aDataEntry) {
		parent::BxDolTwigPageView('bx_groups_view', $oMain, $aDataEntry);
	
		//[begin] - ultimate groups mod from modzzz  
        $this->sSearchResultClassName = 'BxGroupsSearchResult';
        $this->sFilterName = 'bx_groups_filter';

        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/'. $this->aDataEntry['uri'];
        $this->sUrlStart .= (false === strpos($this->sUrlStart, '?') ? '?' : '&'); 

		$this->sUri = $this->aDataEntry['uri'];
		//[end] - ultimate groups mod from modzzz 	
	
	}
	 
	function getBlockCode_Share() {  
 
		$aVars = array (
		    'site_url' => $this->sUrlStart,
			'width' => getParam('bx_groups_facebook_app_width')
		);
		return $this->_oTemplate->parseHtmlByName('block_social_share', $aVars);	 
	}
 
	function getBlockCode_FacebookComments() {  
 
		if(!getParam('bx_groups_facebook_app_key'))
			return;

		$aVars = array (
		    'app_id' => getParam('bx_groups_facebook_app_key'),
			'width' => getParam('bx_groups_facebook_app_width')
		);
		return $this->_oTemplate->parseHtmlByName('block_facebook_comments', $aVars);	 
	}

    /**
     * Profile block with user's location map
     * @param $iEntryId user's id which location is shown on the map
     * @return html with user's location map
     */         
  	function getBlockCode_Map() {

        $iEntryId = (int)$this->aDataEntry['id'];   
		$iAuthorId = (int)$this->aDataEntry['author_id'];   
	 
        $r = $this->_oDb->getProfileById($iEntryId);

        $sBoxContent = '';
        if ($r && $this->_oMain->isAllowedViewLocation ($iEntryId, $r)) {
  
 			$sBaseUri = BX_DOL_URL_ROOT . $this->_oMain->_oConfig->getBaseUri();

			$this->_oTemplate->addInjection('injection_body', 'text',  'onload="load(\''.$sBaseUri.'\', '.$iEntryId.', '.$r['lat'].', '.$r['lng'].');"'); 

			$this->_oTemplate->addJs ('http://maps.google.com/maps/api/js?sensor=false');
			$this->_oTemplate->addJs ('gmap_single.js');
 
            $aVars = array (
                'text' => $r['address'] ? $r['address'] : _t('_bx_groups_the_same_address'), 
            );
            $sBoxContent = $this->_oTemplate->parseHtmlByName('block_map_single', $aVars);
		}
/*
		$sBoxFooter = '';
		if ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) {
			$aVars = array (
				'icon' => $this->_oTemplate->getIconUrl('more.png'),
				'url' => $this->_oConfig->getBaseUri() . "map_edit/{$iEntryId}",
				'title' => _t('_bx_groups_box_footer_edit'),
			);
			$sBoxFooter = $this->_oTemplate->parseHtmlByName('box_footer', $aVars);
			if (!$sBoxContent)
				$sBoxContent = MsgBox(_t('_bx_groups_msg_locations_is_not_defined'));
		}
 */
		if ($sBoxContent || $sBoxFooter)
			return array($sBoxContent, array(), $sBoxFooter);
		return ''; 
	}
 
	function getBlockCode_Info() {
        return $this->_blockInfo ($this->aDataEntry, $this->_oTemplate->blockFields($this->aDataEntry));
    }

	function getBlockCode_Desc() {
        return $this->_oTemplate->blockDesc ($this->aDataEntry);
    }

	function getBlockCode_Photo() {
        return $this->_blockPhoto ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'images'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Video() {
        return $this->_blockVideo ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'videos'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Sound() {
        return $this->_blockSound ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'sounds'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Files() {
        return $this->_blockFiles ($this->_oDb->getMediaIds($this->aDataEntry['id'], 'files'), $this->aDataEntry['author_id']);
    }    

    function getBlockCode_Rate() {
        bx_groups_import('Voting');
        $o = new BxGroupsVoting ('bx_groups', (int)$this->aDataEntry['id']);
        if (!$o->isEnabled()) return '';
        return $o->getBigVoting ($this->_oMain->isAllowedRate($this->aDataEntry));
    }        

    function getBlockCode_Comments() {    
        bx_groups_import('Cmts');
        $o = new BxGroupsCmts ('bx_groups', (int)$this->aDataEntry['id']);
        if (!$o->isEnabled()) return '';
        return $o->getCommentsFirst ();
    }            

	//[begin] - ultimate groups mod from modzzz  
	function getBlockCode_VideoEmbed() { 
	 
	    $sVideoEmbed = trim($this->aDataEntry['video_embed']);
		
		if(!$sVideoEmbed)
			  return;
		
		$aVars = array ( 
			'embed' => $sVideoEmbed 
	    );
	
	    return $this->_oTemplate->parseHtmlByName('embed_block', $aVars);  
	}
  
	function getBlockCode_Local() {    
		return $this->ajaxBrowse('local', $this->_oDb->getParam('bx_groups_perpage_main_recent'),array(),$this->aDataEntry['city'],$this->aDataEntry['id']); 
	}

	function getBlockCode_Other() {    
		return $this->ajaxBrowse('other', $this->_oDb->getParam('bx_groups_perpage_main_recent'),array(),$this->aDataEntry['author_id'],$this->aDataEntry['id']); 
	}

    function ajaxBrowse($sMode, $iPerPage, $aMenu = array(), $sValue = '', $sValue2 = '', $isDisableRss = false, $isPublicOnly = true) {
        $oMain = BxDolModule::getInstance('BxGroupsModule');

        bx_import ('SearchResult', $oMain->_aModule);
        $sClassName = $this->sSearchResultClassName;
        $o = new $sClassName($sMode, $sValue, $sValue2);
        $o->aCurrent['paginate']['perPage'] = $iPerPage; 
        $o->setPublicUnitsOnly($isPublicOnly);

        if (!$aMenu)
            $aMenu = ($isDisableRss ? '' : array(_t('RSS') => array('href' => $o->aCurrent['rss']['link'] . (false === strpos($o->aCurrent['rss']['link'], '?') ? '?' : '&') . 'rss=1', 'icon' => getTemplateIcon('rss.png'))));

        if ($o->isError)
            return array(MsgBox(_t('_Error Occured')), $aMenu);

        if (!($s = $o->displayResultBlock())) 
            return $isPublicOnly ? array(MsgBox(_t('_Empty')), $aMenu) : '';


        $sFilter = (false !== bx_get($this->sFilterName)) ? $this->sFilterName . '=' . bx_get($this->sFilterName) . '&' : '';
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $o->aCurrent['paginate']['totalNum'],
            'per_page' => $o->aCurrent['paginate']['perPage'],
            'page' => $o->aCurrent['paginate']['page'],
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $this->sUrlStart . $sFilter . 'page={page}&per_page={per_page}\');',
        ));
        $sAjaxPaginate = $oPaginate->getSimplePaginate($this->_oConfig->getBaseUri() . $o->sBrowseUrl);

        return array(
            $s, 
            $aMenu,
            $sAjaxPaginate,
            '');
    } 
    
    function _blockInfo ($aData, $sFields = '') {

        $aAuthor = getProfileInfo($aData['author_id']);

        $aVars = array (
            'author_thumb' => get_member_thumbnail($aAuthor['ID'], 'none'),
            'date' => getLocaleDate($aData['created'], BX_DOL_LOCALE_DATE_SHORT),
            'date_ago' => defineTimeInterval($aData['created']),
            'cats' => $this->_oTemplate->parseCategories($aData['categories']),
            'tags' => $this->_oTemplate->parseTags($aData['tags']),
			'views' => $aData['views'],
            'fields' => $sFields,
            'author_username' => $aAuthor['NickName'],
            'author_url' => $aAuthor ? getProfileLink($aAuthor['ID']) : 'javascript:void(0)',
        );
        return $this->_oTemplate->parseHtmlByName('entry_view_block_info', $aVars);
    }  
    //[end] - ultimate groups mod from modzzz 
 
  


    function getBlockCode_Actions() {
        global $oFunctions;

        if ($this->_oMain->_iProfileId || $this->_oMain->isAdmin()) {

            $oSubscription = new BxDolSubscription();
            $aSubscribeButton = $oSubscription->getButton($this->_oMain->_iProfileId, 'bx_groups', '', (int)$this->aDataEntry['id']);

			$isFan = $this->_oDb->isFan((int)$this->aDataEntry['id'], $this->_oMain->_iProfileId, 0) || $this->_oDb->isFan((int)$this->aDataEntry['id'], $this->_oMain->_iProfileId, 1);

            $aInfo = array (
                'BaseUri' => $this->_oMain->_oConfig->getBaseUri(),
                'iViewer' => $this->_oMain->_iProfileId,
                'ownerID' => (int)$this->aDataEntry['author_id'],
                'ID' => (int)$this->aDataEntry['id'],
                'URI' => $this->aDataEntry['uri'],
                'ScriptSubscribe' => $aSubscribeButton['script'],
                'TitleSubscribe' => $aSubscribeButton['title'], 
                'TitleEdit' => $this->_oMain->isAllowedEdit($this->aDataEntry) ? _t('_bx_groups_action_title_edit') : '',
                'TitleDelete' => $this->_oMain->isAllowedDelete($this->aDataEntry) ? _t('_bx_groups_action_title_delete') : '',
                'TitleJoin' => $this->_oMain->isAllowedJoin($this->aDataEntry) ? ($isFan ? _t('_bx_groups_action_title_leave') : _t('_bx_groups_action_title_join')) : '',
                'TitleInvite' => $this->_oMain->isAllowedSendInvitation($this->aDataEntry) ? _t('_bx_groups_action_title_invite') : '',
                'TitleShare' => $this->_oMain->isAllowedShare($this->aDataEntry) ? _t('_bx_groups_action_title_share') : '',
                'TitleBroadcast' => $this->_oMain->isAllowedBroadcast($this->aDataEntry) ? _t('_bx_groups_action_title_broadcast') : '',
                'TitleEventAdd' => ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) ? _t('_bx_groups_action_title_add_event') : '',
                'TitleSponsorAdd' => ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) ? _t('_bx_groups_action_title_add_sponsor') : '',
                'TitleNewsAdd' => ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) ? _t('_bx_groups_action_title_add_news') : '',
	            'TitleVenueAdd' => ($this->_oMain->isAdmin() || $this->_oMain->isEntryAdmin($this->aDataEntry)) ? _t('_bx_groups_action_title_add_venue') : '',
			 
				'AddToFeatured' => $this->_oMain->isAllowedMarkAsFeatured($this->aDataEntry) ? ($this->aDataEntry['featured'] ? _t('_bx_groups_action_remove_from_featured') : _t('_bx_groups_action_add_to_featured')) : '',

				'TitlePurchaseFeatured' => $this->_oMain->isAllowedPurchaseFeatured($this->aDataEntry) ? ($this->aDataEntry['featured'] ? _t('_bx_groups_action_title_extend_featured') : _t('_bx_groups_action_title_purchase_featured')) : '',
 
                'TitleManageFans' => $this->_oMain->isAllowedManageFans($this->aDataEntry) ? _t('_bx_groups_action_manage_fans') : '',
                'TitleUploadPhotos' => $this->_oMain->isAllowedUploadPhotos($this->aDataEntry) ? _t('_bx_groups_action_upload_photos') : '',
                'TitleUploadVideos' => $this->_oMain->isAllowedUploadVideos($this->aDataEntry) ? _t('_bx_groups_action_upload_videos') : '',
                'TitleUploadSounds' => $this->_oMain->isAllowedUploadSounds($this->aDataEntry) ? _t('_bx_groups_action_upload_sounds') : '',
                'TitleUploadFiles' => $this->_oMain->isAllowedUploadFiles($this->aDataEntry) ? _t('_bx_groups_action_upload_files') : '',
            );

            if (!$aInfo['TitleEdit'] && !$aInfo['TitleDelete'] && !$aInfo['TitleJoin'] && !$aInfo['TitleInvite'] && !$aInfo['TitleShare'] && !$aInfo['TitleBroadcast'] && !$aInfo['AddToFeatured'] && !$aInfo['TitlePurchaseFeatured'] && !$aInfo['TitleManageFans'] && !$aInfo['TitleUploadPhotos'] && !$aInfo['TitleUploadVideos'] && !$aInfo['TitleUploadSounds'] && !$aInfo['TitleUploadFiles']) 
                return '';

            return $oSubscription->getData() . $oFunctions->genObjectsActions($aInfo, 'bx_groups');
        } 

        return '';
    }    

    function getBlockCode_Fans() {
        return parent::_blockFans ($this->_oDb->getParam('bx_groups_perpage_view_fans'), 'isAllowedViewFans', 'getFans');
    }            

    function getBlockCode_FansUnconfirmed() {
        return parent::_blockFansUnconfirmed (BX_GROUPS_MAX_FANS);
    }

	function getBlockCode_Forum() {
  		
		$iGroupId = (int)$this->aDataEntry['id'];

		$aPosts = $this->_oDb->getAll("SELECT e.`title`, f.`forum_uri`, p.`user`, p.`post_text`, t.`topic_uri`, t.`topic_title`,p.`when` FROM `bx_groups_forum` f, `bx_groups_forum_topic` t, `bx_groups_forum_post` p, `bx_groups_main` e WHERE p.`topic_id`=t.`topic_id` AND t.`forum_id`=f.`forum_id` AND e.`ID`=f.`entry_id` AND f.`forum_id`=$iGroupId ORDER BY  p.`when` LIMIT 5");

		if(empty($aPosts))
			return;
				
		$aVars['bx_repeat:entries'] = array();
  		foreach($aPosts as $aEachPost){

			$sForumUri = $aEachPost['forum_uri'];
			$sTopic = $aEachPost['topic_title']; 
			$sTopicUri = $aEachPost['topic_uri'];
			$sPostText = $aEachPost['post_text']; 
			$sDate = defineTimeInterval($aEachPost['when']); 
			$sGroupName = $aEachPost['title']; 
 			$sPoster = $aEachPost['user']; 

			$iLimitChars = (int)getParam('bx_groups_forum_max_preview');
			if (strlen($sPostText) > $iLimitChars) {
				$sLinkMore = '...';
				$sPostText = process_line_output(mb_substr(strip_tags($sPostText), 0, $iLimitChars)) . $sLinkMore;
			}
 
			$sGroupUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() .'view/' . $sForumUri;
			$sTopicUrl = BX_DOL_URL_ROOT . 'forum/groups/forum/'.$sForumUri.'-0.htm#topic/'.$sTopicUri.'.htm';
	
			$aVars['bx_repeat:entries'][] = array( 
							'topic_url' => $sTopicUrl, 
							'topic' => $sTopic, 
							'post' => $sPostText, 
							'group_name' => $sGroupName, 
							'group_url' => $sGroupUrl, 
							'post_date' => $sDate,
							'nicklink' => getProfileLink(getID($sPoster)),
							'nickname' => $sPoster, 
						);
		}

		$sCode = $this->_oTemplate->parseHtmlByName('group_view_forum', $aVars);  

		return $sCode;
	}
 
   function getBlockCode_News () {
 
        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() .  'news/browse/' . $this->sUri . '?';
  
        $this->_oTemplate->addCss('unit.css');

        return $this->ajaxBrowseSubProfile(
            'news',
            'news',
            $this->_oDb->getParam('bx_groups_perpage_browse_subitems'), 
            array(), $this->sUri, true, false 
        );
 
    }

    function getBlockCode_Venues () {
 
        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() .  'venue/browse/' . $this->sUri . '?';
  
        $this->_oTemplate->addCss('unit.css');

        return $this->ajaxBrowseSubProfile(
            'venue',
            'venues',
            $this->_oDb->getParam('bx_groups_perpage_browse_subitems'), 
            array(), $this->sUri, true, false 
        );
 
    }

    function getBlockCode_Sponsors () {
 
        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() .  'sponsor/browse/' . $this->sUri . '?';
  
        $this->_oTemplate->addCss('unit.css');

        return $this->ajaxBrowseSubProfile(
            'sponsor',
            'sponsors',
            $this->_oDb->getParam('bx_groups_perpage_browse_subitems'), 
            array(), $this->sUri, true, false 
        );
 
    }

    function getBlockCode_Events () {
 
        $this->sUrlStart = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() .  'event/browse/' . $this->sUri . '?';
  
        $this->_oTemplate->addCss('unit.css');

        return $this->ajaxBrowseSubProfile(
            'event',
            'events',
            $this->_oDb->getParam('bx_groups_perpage_browse_subitems'), 
            array(), $this->sUri, true, false 
        );
 
    }
   
    function ajaxBrowseSubProfile($sType, $sMode, $iPerPage, $aMenu = array(), $sValue = '', $isDisableRss = false, $isPublicOnly = true) {

        bx_import ('SearchResult', $this->_oMain->_aModule);
        $sClassName = $this->sSearchResultClassName;
        $o = new $sClassName($sMode, $sValue);
        $o->aCurrent['paginate']['perPage'] = $iPerPage; 
        $o->setPublicUnitsOnly($isPublicOnly);
 
        if ($o->isError)
            return array(MsgBox(_t('_Error Occured')), $aMenu);
 
        if (!($s = $o->displaySubProfileResultBlock($sType))) {
             return array(MsgBox(_t('_Empty')), $aMenu);
		} 

        $sFilter = (false !== bx_get($this->sFilterName)) ? $this->sFilterName . '=' . bx_get($this->sFilterName) . '&' : '';
        $oPaginate = new BxDolPaginate(array(
            'page_url' => 'javascript:void(0);',
            'count' => $o->aCurrent['paginate']['totalNum'],
            'per_page' => $o->aCurrent['paginate']['perPage'],
            'page' => $o->aCurrent['paginate']['page'],
            'on_change_page' => 'return !loadDynamicBlock({id}, \'' . $this->sUrlStart . $sFilter . 'page={page}&per_page={per_page}\');',
        ));
        $sAjaxPaginate = $oPaginate->getSimplePaginate($this->_oConfig->getBaseUri() . $o->sBrowseUrl);

        return array(
            $s, 
            $aMenu,
            $sAjaxPaginate,
            '');
    }    
 
	 function getBlockCode_CustomRSS() {

		$iGroupId = (int)$this->aDataEntry['id'];
		$aRSS = $this->_oDb->getRss($iGroupId);

		if(empty($aRSS))
			  return;
 
		$sFeeds = '';
		$aVars = array();
		foreach($aRSS as $aEachRSS){

			  $sRSSTopic = trim($aEachRSS['name']);
			  $sRSSLink = trim($aEachRSS['url']);

			  $iCounter = 1;
			  $aVars['bx_repeat:entries'] = array();

			  $doc = new DOMDocument();
			  @$doc->load($sRSSLink);

			  foreach ($doc->getElementsByTagName('item') as $node) {
 
				$aVars['bx_repeat:entries'][] = array ( 
				  'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
				  'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
				  'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
				  'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
				  );
	 
				if($iCounter == (int)getParam('bx_groups_perpage_rss_feed')) break;
	 
				$iCounter++;
			 }

			 if($iCounter > 1){
				$aVars['topic'] = $sRSSTopic;

				$sFeeds .= $this->_oTemplate->parseHtmlByName('group_rss', $aVars); 
			 }
		}

	    return $sFeeds; 
	}
 
    function getCode() {

        $this->_oMain->_processFansActions ($this->aDataEntry, BX_GROUPS_MAX_FANS);

        return parent::getCode();
    }

}

?>